package log

import (
	"errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
	"higame/config"
)

type IntegralLogSchema struct {
	ID       primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
	UUID     string             `json:"uuid" bson:"uuid" form:"uuid"`
	AddTime  int64              `json:"add_time" bson:"add_time" form:"add_time"`
	Username string             `json:"username" bson:"username" form:"username"`
	Integral int64              `json:"integral" bson:"integral" form:"integral"`
	Text     string             `json:"text" bson:"text"`
	Other    string             `json:"other" bson:"other"`
	Remark   string             `json:"remark" bson:"remark"`
}

var colName = config.Db.Collection.LogIntegral

func NewIntegralLogSchema() *IntegralLogSchema {
	return &IntegralLogSchema{}
}

func ParseIntegralLog(data bson.M) (*IntegralLogSchema, error) {
	u := NewIntegralLogSchema()
	if err := db.ToStruct(data, u); err != nil {
		return nil, err
	}
	return u, nil
}

func AddOneIntegralLog(log *IntegralLogSchema) error {
	logI := db.InsertOne(colName, log)
	if !logI {
		return errors.New("添加日志失败，可能是数据连接有问题")
	}
	return nil
}

func FindManyIntegralLogByUsername(username string) []bson.M {
	opts := new(options.FindOptions)
	list := db.FindMany(colName, bson.M{
		"username": username,
	}, opts.SetLimit(20),
		opts.SetSkip(0),
		opts.SetSort(bson.M{
			"add_time": -1,
		}))
	return list
}

func FindManyIntegralLog(pageNum int64, filter interface{}) []bson.M {
	if pageNum > 0 {
		pageNum = pageNum - 1
	}
	opts := new(options.FindOptions)
	list := db.FindMany(colName, filter,
		opts.SetSkip(pageNum*20),
		opts.SetLimit(20),
		opts.SetSort(bson.M{
			"add_time": -1,
		}))
	return list
}

func CountIntegralLog(filter interface{}) (int64, error) {
	return db.Count(colName, filter), nil
}
